﻿using System;
using System.Text.RegularExpressions;
using JetBrains.Annotations;

namespace WikiDoc.Lines
{
    /// <summary>
    /// 表示一个 横线行 “-----”
    /// </summary>
    public class HorizonLine : WikiLine
    {
        /// <summary>
        /// 减号数量
        /// </summary>
        /// <value>The level.</value>
        public int Level { get; private set; }

        /// <summary>
        /// 初始化 <see cref="HorizonLine"/> 类的新实例.
        /// </summary>
        /// <param name="line"></param>
        /// <param name="level"></param>
        protected HorizonLine(string line, int level) : base(line, LineTypes.HorizonLine)
        {
            if (line == null) throw new ArgumentNullException("line");
            if (level <= 0)
            {
                throw new ArgumentOutOfRangeException("level", level, "level 必须大于 0");
            }

            Line = line;
            Level = level;
        }

        /// <summary>
        /// 横线，单独的一行至少4个连续减号
        /// </summary>
        public static readonly Regex Pattern = new Regex(
            @"\A \s* (\-{4,}|－{4,}) \s* \z",
            RegexOptions.Compiled |
            RegexOptions.CultureInvariant |
            RegexOptions.Singleline |
            RegexOptions.IgnorePatternWhitespace);

        [CanBeNull]
        public static WikiLine TryParse([CanBeNull] string line)
        {
            if (line == null) return null;

            var match = Pattern.Match(line);

            return match.Success
                       ? new HorizonLine(line,
                                         match.Groups[1].Length)
                       : null;
        }
    }
}
